package servlet;


import entity.Man;
import service.Manservice;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

@WebServlet("/mans")
public class Manservlet extends HttpServlet {
    private Manservice manservice = new Manservice();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            List<Man> mans = manservice.getAll();
            request.setAttribute("mans", mans);
            request.getRequestDispatcher("/index.jsp").forward(request, response);
        } catch (SQLException e) {
            throw new ServletException(e);
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String action  = request.getParameter("action");
        try {
            if ("add".equals(action)){
                String name=request.getParameter("name");
                int age=Integer.parseInt(request.getParameter("age"));
                String diZhi=request.getParameter("diZhi");
                String major=request.getParameter("major");

                Man student=new Man(name,age,diZhi,major);
                manservice.addMan(student);
            }else if ("update".equals(action)){

                int id=Integer.parseInt(request.getParameter("id"));
                String name=request.getParameter("name");
                int age=Integer.parseInt(request.getParameter("age"));
                String gender=request.getParameter("diZhi");
                String major=request.getParameter("major");

                Man student=new Man();
                student.setId(id);
                student.setName(name);
                student.setAge(age);
                student.setDiZhi(gender);
                student.setMajor(major);
                manservice.UpdateMan(student);
            }else if ("delete".equals(action)){
                int id=Integer.parseInt(request.getParameter("id"));
                manservice.DeleteMan(id);
            }
            response.sendRedirect(request.getContextPath()+"/mans");
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }
}
